<script>
import { mapState, mapMutations } from 'vuex';
// import { token, imInfo } from '@/utils/token.js';
import { token, userInfo, imInfo } from "@/utils/token.js"
import { imKey } from '@/config.js';
// import IMController from '@/libs/imController.js';
	import { initEid } from './mp_ecard_sdk/main';

export default {
	globalData: {
		systemInfo: {}, //系统详情
		scrollHeight: 812, //滚动高度
		emitter: null,
		nim: null,
		netcall: null,
		netcallController: null,
		videoContainerSize: {},
		appKey: imKey,
		role: 0, //当前身份 0患者  1医生 2药师
		parentUserId: null,
		parentDoctorId: null,
		parentAgencyId: null
	},

	onLaunch: function(options) {
		initEid();
		// const verify = require('./wxcomponents/verify_mpsdk/main.js');
		// verify.init();
		if (options.query.tt == '123456') {
			token.clear();
		}
		
		// imInfo.set({
		// 	accid: "1447748833400459264",
		// 	name: "。",
		// 	token: "9c959d2076297480dccc77ef5f71f2fd"
		// }, Date.parse(new Date()) + (86400000 * 29))
		
		// userInfo.set({
		// 	avatar: "https://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83erkBWicibOBTtnQOJNe5tgc5Mb4KPket3S4ePGhwdGrkwSa1O6cSdWS9H9L6uNZddjHVZpdNibgoMttA/132",
		// 	birthday: null,
		// 	city: "",
		// 	createTime: "2021-10-08",
		// 	currentRole: 1,
		// 	delFlag: null,
		// 	doctorName: null,
		// 	email: null,
		// 	id: "1447748833400459264",
		// 	idNum: null,
		// 	imToken: "dd451996528d54bb3e225097f56dff65",
		// 	openId: "o_u-K5SweiqPq9dRMEnZrezoH6sM",
		// 	password: null,
		// 	phone: null,
		// 	province: "",
		// 	realname: null,
		// 	role: "0,1,2",
		// 	salt: "1446446839876423681",
		// 	sex: 0,
		// 	status: null,
		// 	unionId: null,
		// 	updateBy: null,
		// 	updateTime: null,
		// 	username: "哎呦喂",
		// 	visitNumber: null
		// }, Date.parse(new Date()) + (86400000 * 29));
		
		
		// token.set(
		// "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MzYwOTA0MDMsInVzZXJuYW1lIjoib191LUs1WmVScmExbkg1QmJhdzVVZ05xZTB0WSJ9.qNC81SQgILUyZN5Qaz8b7QpPjg9LNRH9HQ5hnQEsZKY",
		// 	 Date.parse(new Date()) + (86400000 * 29)
		// );

		console.log('App Launch');
		this.initApp();
	},
	onShow: function(options) {
		console.log('App Show');
	},
	onHide: function() {
		console.log('App Hide');
	},
	computed: {
		...mapState({
			longitude: state => state.longitude,
			latitude: state => state.latitude
		})
	},
	methods: {
		...mapMutations({
			setPositionName: 'setPositionName',
			setPositionRegion: 'setPositionRegion',
			setPositionAdcode: 'setPositionAdcode',
			setLongitude: 'setLongitude',
			setLatitude: 'setLatitude'
		}),
		initApp(options) {
			//查询小程序更新
			this.updateManager();
			//初始化系统信息
			this.setScrollHeight();
			//初始化定位信息
			this.getLocation();

			/*
			setInterval(() => {
				if (token.get()) {
					this.$api.findRoom({}).then(res => {
						if (res.code == 200 && res.result) {
							//有房间邀请通话
							let cid = res.result;
							let thisAccid;
							let nickName;
							
							this.$api.roomInfo({
								params:{
									cid:cid
								}
							}).then(succ => {
								let channelName = succ.result.cname
								
								
								this.$api.getUserDetail({}).then(success => {
									if (success.code == 200) {
										let role = success.result.currentRole;
										
										this.$api.getDoctorInfo({}).then(res => {
											if (res.code == 200) {
												if (role == 0) {
													//患者
													thisAccid = success.result.id;
													nickName = success.result.username;
												} else {
													thisAccid = res.result.id;
													nickName = res.result.doctorName;
												}
												
												// const url = '/pages-im/videoCall2/videoCall2';
												const url = '/pages-txy-im/videoCall2/videoCall2';
												const queryParams = {
													originChannelName: channelName,
													channelName: channelName,
													uid: thisAccid,
													channelId: cid,
													token: '', // 如果是非安全模式，请传入空字符串
													nickName: nickName,
													openCamera: true,
													openMicrophone: true,
													resolution: 'FHD',
													audioQuality: 'high',
													videoWidth: 720,
													videoHeight: 1280,
													minBitrate: 1500,
													maxBitrate: 2000,
													debug: false,
													type:1
												};
												
												uni.setStorageSync("queryParams",JSON.stringify(queryParams))
												const finalUrl = Object.keys(queryParams).reduce((prev, cur) => {
													return `${prev}${prev === url ? '?' : '&'}${cur}=${queryParams[cur]}`;
												}, url);
											
												uni.navigateTo({ url: finalUrl });
											}
										});
									}
								});
							})
							//删除房间
							this.imTokenRemoveRoom();
						}
					});
				}
			}, 3000);
			*/
		},

		gotoLogin() {
			uni.reLaunch({
				url: '/pages/login/login'
			});
		},

		//删除房间
		imTokenRemoveRoom() {
			this.$api.imTokenRemoveRoom({}).then(res => {
			});
		},

		//初始化系统信息
		setScrollHeight() {
			let systemInfo = wx.getSystemInfoSync();
			this.globalData.videoContainerSize = {
				width: systemInfo.windowWidth,
				height: systemInfo.windowHeight
			};
			this.globalData.systemInfo = systemInfo;
			this.globalData.scrollHeight = this.pxTransformRpx(systemInfo.windowHeight);
		},

		//获取定位
		getLocation() {
			uni.getLocation({
				type: 'gcj02',
				success: res => {
					this.setLongitude(res.longitude);
					this.setLatitude(res.latitude);
					// this.getRegeo();
					// uni.$emit('getLocation');
				},
				fail: err => {
					uni.showToast({
						title: '定位获取失败',
						icon: 'none'
					});
				}
			});
		},

		//获取位置详情
		getRegeo() {
			this.$api
				.regeoGeocode({
					params: {
						location: this.longitude + ',' + this.latitude,
						extensions: 'all'
					}
				})
				.then(res => {
					const positionName = res.regeocode.addressComponent.building.name;
					this.setPositionName(positionName.length > 0 ? positionName : res.regeocode.aois[0].name);
					this.setPositionRegion(res.regeocode.addressComponent.district);
					this.setPositionAdcode(res.regeocode.addressComponent.adcode);
				})
				.catch(err => {
					uni.showToast({
						title: '定位信息获取失败',
						icon: 'none'
					});
				});
		},

		//px -rpx 转换
		pxTransformRpx(px) {
			return px * (750 / this.globalData.systemInfo.windowWidth);
		},

		rpxTransformpx(rpx) {
			return rpx / (750 / this.globalData.systemInfo.windowWidth);
		},

		//小程序检查更新
		updateManager() {
			const updateManager = uni.getUpdateManager();
			updateManager.onCheckForUpdate(res => {
				// 请求完新版本信息的回调
				// console.log(res.hasUpdate);
			});

			updateManager.onUpdateReady(res => {
				uni.showModal({
					title: '更新提示',
					content: '新版本已经准备好，是否重启应用？',
					success: res => {
						if (res.confirm) {
							// 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
							updateManager.applyUpdate();
						}
					}
				});
			});

			updateManager.onUpdateFailed(res => {
				uni.showToast({
					title: '新版本下载失败',
					icon: 'none'
				});
			});
		}
	}
};
</script>

<style lang="less">
@import './common/less/base';
</style>
